﻿using ExpressesClass.BestApi.Utils;
using ExpressesClass.Method;
using ExpressesClass.Model;
using OFFICE_Helper.Util;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace OFFICE_Helper.Forms
{
    public partial class BatchForm : Form
    {
        #region 变量
        private MainForm mainForm;

        private List<Kddh> list_kddhs;
        private List<Company> list_companys;
        private List<string> list_kdcompanys;

        private DataTable dt_model;

        private string payMethod;
        private string sendTypes;
        private string isReturnNo;
        private string bestSendTypes;
        private string sfSendTypes;
        private string sfPayMethod;
        private string sfIsReturnNo;
        #endregion

        #region 方法
        public BatchForm(MainForm mainForm)
        {
            InitializeComponent();
            this.mainForm = mainForm;
        }
        private void BatchForm_Load(object sender, EventArgs e)
        {
            mainForm.btn_batch.Enabled = false;

            list_kddhs = new List<Kddh>();

            string companys = ConfigurationManager.AppSettings["companys"].ToString();
            list_companys = JsonUtil.parse<List<Company>>(companys);
            string kdcompanys = ConfigurationManager.AppSettings["kdcompanys"].ToString();
            list_kdcompanys = JsonUtil.parse<List<string>>(kdcompanys);

            dt_model = new DataTable();
            dt_model.Columns.Add("快递公司");
            dt_model.Columns.Add("寄件人姓名");
            dt_model.Columns.Add("寄件人联系电话");
            dt_model.Columns.Add("寄件人省份");
            dt_model.Columns.Add("寄件人城市");
            dt_model.Columns.Add("寄件人区县");
            dt_model.Columns.Add("寄件人地址");
            dt_model.Columns.Add("包裹数量");
            dt_model.Columns.Add("收件人姓名");
            dt_model.Columns.Add("收件人联系电话");
            dt_model.Columns.Add("收件人省份");
            dt_model.Columns.Add("收件人城市");
            dt_model.Columns.Add("收件人区县");
            dt_model.Columns.Add("收件人地址");

            payMethod = ConfigurationManager.AppSettings["payMethod"].ToString();
            sendTypes = ConfigurationManager.AppSettings["sendTypes"].ToString();
            isReturnNo = ConfigurationManager.AppSettings["isReturnNo"].ToString();
            bestSendTypes = ConfigurationManager.AppSettings["bestSendTypes"].ToString();
            sfSendTypes = ConfigurationManager.AppSettings["sfSendTypes"].ToString();
            sfPayMethod = ConfigurationManager.AppSettings["sfPayMethod"].ToString();
            sfIsReturnNo = ConfigurationManager.AppSettings["sfIsReturnNo"].ToString();
        }
        public bool Check()
        {
            if (list_kddhs.Count == 0)
            {
                MessageBox.Show("条目为空,请填写.", "提示");
                return false;
            }
            foreach (Kddh k in list_kddhs)
            {
                if (!list_kdcompanys.Contains(k.kdCompanys))
                {
                    MessageBox.Show("快递公司:[" + k.kdCompanys + "]填写错误,请重填.", "提示");
                    return false;
                }
                if (!int.TryParse(k.itemCount, out int i))
                {
                    MessageBox.Show("包裹数量:[" + k.itemCount + "]填写错误,请重填.", "提示");
                    return false;
                }
                if (string.IsNullOrEmpty(k.sendMan)
                    || string.IsNullOrEmpty(k.sendManPhone)
                    || string.IsNullOrEmpty(k.sendProvince)
                    || string.IsNullOrEmpty(k.sendCity)
                    || string.IsNullOrEmpty(k.sendCounty)
                    || string.IsNullOrEmpty(k.sendManAddress)
                    || string.IsNullOrEmpty(k.receiveMan)
                    || string.IsNullOrEmpty(k.receiveManPhone)
                    || string.IsNullOrEmpty(k.receiveProvince)
                    || string.IsNullOrEmpty(k.receiveCity)
                    || string.IsNullOrEmpty(k.receiveCounty)
                    || string.IsNullOrEmpty(k.receiveManAddress))
                {
                    MessageBox.Show("必填项不能为空,请填写.", "提示");
                    return false;
                }
            }
            return true;
        }
        private bool CheckTable(DataTable dt)
        {
            foreach (DataColumn col in dt_model.Columns)
            {
                if (!dt.Columns.Contains(col.ColumnName))
                {
                    MessageBox.Show("必须包含[" + col.ColumnName + "]列,请填写.", "提示");
                    return false;
                }
            }
            return true;
        }
        private void SetColor(DataGridView dgv)
        {
            for (int r = 0; r < dgv.Rows.Count; r++)
            {
                if (!list_kdcompanys.Contains(dgv.Rows[r].Cells["快递公司"].Value.ToString()))
                {
                    dgv.Rows[r].Cells["快递公司"].Style.BackColor = Color.Red;
                }
                if (!int.TryParse(dgv.Rows[r].Cells["包裹数量"].Value.ToString(), out int i))
                {
                    dgv.Rows[r].Cells["包裹数量"].Style.BackColor = Color.Red;
                }
                for (int c = 0; c < dgv.Columns.Count; c++)
                {
                    if (string.IsNullOrEmpty(dgv.Rows[r].Cells[c].Value.ToString()))
                    {
                        dgv.Rows[r].Cells[c].Style.BackColor = Color.Red;
                    }
                }
            }
        }
        private Kddh Package(Kddh kddh)
        {
            Kddh k = new Kddh();
            k.sendMan = kddh.sendMan;
            k.sendManPhone = kddh.sendManPhone;
            k.sendManAddress = kddh.sendManAddress;
            k.sendPostcode = "";
            k.sendProvince = kddh.sendProvince;
            k.sendCity = kddh.sendCity;
            k.sendCounty = kddh.sendCounty;
            k.sendCompany = list_companys[0].Name;

            k.receiveMan = kddh.receiveMan;
            k.receiveManPhone = kddh.receiveManPhone;
            k.receiveManAddress = kddh.receiveManAddress;
            k.receivePostcode = "";
            k.receiveProvince = kddh.receiveProvince;
            k.receiveCity = kddh.receiveCity;
            k.receiveCounty = kddh.receiveCounty;
            k.receiveCompany = "";

            k.itemCount = kddh.itemCount;
            k.itemName = "";
            k.itemWeight = "0.00";
            k.remark = "";
            k.bm = "";
            k.wzh = "";
            k.kdCompanys = kddh.kdCompanys;

            string s_sendtypes = sendTypes;
            string s_payMethod = payMethod;
            string s_returnNo = isReturnNo;

            if (kddh.kdCompanys == "百世快递")
            {
                s_sendtypes = bestSendTypes;
            }
            else if (kddh.kdCompanys == "顺丰快递")
            {
                s_sendtypes = sfSendTypes;
                s_payMethod = sfPayMethod;
                s_returnNo = sfIsReturnNo;
            }
            List<string> l_sendtypes = JsonUtil.parse<List<string>>(s_sendtypes);
            List<string> l_payMethod = JsonUtil.parse<List<string>>(s_payMethod);
            List<string> l_returnNo = JsonUtil.parse<List<string>>(s_returnNo);

            k.shipName = l_sendtypes[0];
            k.shipVal = "0.00";
            k.payMethod = l_payMethod[0];
            k.isReturnNo = l_returnNo[0];

            k = TypeControl.Format(k);
            return k;
        }
        #endregion

        #region 事件
        private void btn_model_Click(object sender, EventArgs e)
        {
            DataTable dt = dt_model.Clone();
            foreach (DataColumn col in dt.Columns)
            {
                col.DataType = typeof(string);
            }
            DataRow row = dt.NewRow();
            row["快递公司"] = list_kdcompanys[0];
            row["寄件人姓名"] = list_companys[0].Name;
            row["寄件人联系电话"] = list_companys[0].Phone;
            row["寄件人省份"] = list_companys[0].Province;
            row["寄件人城市"] = list_companys[0].City;
            row["寄件人区县"] = list_companys[0].County;
            row["寄件人地址"] = list_companys[0].Address;
            row["包裹数量"] = "1";
            dt.Rows.Add(row);

            ExcelHelper.ExportDataToExcel(dt, "快递申请导入模板");
        }
        private void btn_open_Click(object sender, EventArgs e)
        {
            list_kddhs.Clear();
            dgv.DataSource = null;

            DataTable dt = ExcelHelper.ExcelToDataTable();
            if (dt != null && dt.Rows.Count > 0 && CheckTable(dt))
            {
                dgv.DataSource = dt;
                SetColor(dgv);

                foreach (DataRow row in dt.Rows)
                {
                    Kddh k = new Kddh();
                    k.kdCompanys = row["快递公司"].ToString();
                    k.sendMan = row["寄件人姓名"].ToString();
                    k.sendManPhone = row["寄件人联系电话"].ToString();
                    k.sendProvince = row["寄件人省份"].ToString();
                    k.sendCity = row["寄件人城市"].ToString();
                    k.sendCounty = row["寄件人区县"].ToString();
                    k.sendManAddress = row["寄件人地址"].ToString();
                    k.itemCount = row["包裹数量"].ToString();
                    k.receiveMan = row["收件人姓名"].ToString();
                    k.receiveManPhone = row["收件人联系电话"].ToString();
                    k.receiveProvince = row["收件人省份"].ToString();
                    k.receiveCity = row["收件人城市"].ToString();
                    k.receiveCounty = row["收件人区县"].ToString();
                    k.receiveManAddress = row["收件人地址"].ToString();
                    list_kddhs.Add(k);
                }
            }
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            if (Check())
            {
                bool re = true;

                WaitForm f = new WaitForm((obj, args) =>
                {
                    WaitForm waitForm = obj as WaitForm;

                    for (int i = 0; i < list_kddhs.Count; i++)
                    {
                        waitForm.SetText("请稍候...(" + i.ToString() + "/" + list_kddhs.Count.ToString() + ")");
                        Kddh k = Package(list_kddhs[i]);
                        if (!ExpressUtil.GetBatchMailNo(k))
                        {
                            re = false;
                            break;
                        }
                        Thread.Sleep(500);
                    }
                });
                f.ShowDialog(this);
                if (re)
                {
                    MessageBox.Show("获取快递电子面单成功.", "提示");
                }
            }
        }
        private void BatchForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            mainForm.btn_batch.Enabled = true;
        }
        #endregion
    }
}
